package classes
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.geom.Matrix;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import mx.controls.ProgressBar;
	import mx.controls.ProgressBarMode;
	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	import mx.events.ResizeEvent;

	public class image_class extends UIComponent
	{
		private var image:BitmapData;
		
		private var _progressBar:ProgressBar;        
        private var _progressPercentWidth:Number = 80;
        private var _progressHeight:Number = 20;
        
        private var timer:Timer;
        [Bindable] public var image_loader:Loader;
		//public var _loader:loader_class;
		
		private var _loaded_bytes:Number = 0;
		private var _total_bytes:Number = 0;
		
		public function image_class()
		{
			super();
		}
		
		private var _url:String = '';
		public function set url(value:String): void {
			this._url = value;
			load_image();
		}
		public function get url(): String {
			return this._url;
		}
		
		private var _type:String = '';
		public function set type(value:String): void {
			this._type = value;
		}
		public function get type(): String {
			return _type;
		}
		
		private var _hasloader:Boolean = true;
		public function set hasloader(value:Boolean): void {
			this._hasloader = value;
		}
		public function get hasloader(): Boolean {
			return this._hasloader;
		}
		
		
		private function load_image(): void {
			var request:URLRequest = new URLRequest(this.url);
		 	image_loader = new Loader();
		 	image_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, image_load_complete_listener);
		 	image_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, image_progress);
		 	
		 	if(this.hasloader){
			 	image_loader.contentLoaderInfo.addEventListener( ResizeEvent.RESIZE, resizeHandler );
	            image_loader.contentLoaderInfo.addEventListener( Event.OPEN, openHandler );
	            image_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeHandler );
	            image_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
	            image_loader.contentLoaderInfo.addEventListener( SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler );
	   		}
		 	// add other listeners here
		 	image_loader.load(request);
		 	
		 	
		}
		
		public function get_loaded_bytes(): Number {
			return this._loaded_bytes;
		}
		
		public function get_total_bytes(): Number {
			return this._total_bytes;
		}
		
		private function image_progress(evt:ProgressEvent): void {
			//this.dispatchEvent( new ProgressEvent(ProgressEvent.PROGRESS, true, false, evt.bytesLoaded, evt.bytesTotal));
			this._loaded_bytes = evt.bytesLoaded;
			this._total_bytes = evt.bytesTotal;
		}
		
		
		
		private function image_load_complete_listener(evt:Event): void {
			image = Bitmap(evt.currentTarget.content).bitmapData;
			//resize image
			if(this.type == 'RESIZE')
				this.resize_image();
			else if(this.type == 'SCALE')
				this.scale_image();
		}
		
		private function resize_image(): void {
			var mtrx:Matrix = new Matrix();
		 	mtrx.scale(this.width/image.width, this.height/image.height);
		 	var new_image:BitmapData = new BitmapData(this.width, this.height);
		 	//this.graphics.clear();
		 	//this.graphics.beginBitmapFill(image, mtrx, false);
		 	//this.graphics.drawRect(0,0,this.width,this.height);
		 	//this.graphics.endFill();
		 	new_image.draw(image, mtrx);
		 	var new_bitmap:Bitmap = new Bitmap(new_image);
		 	new_bitmap.smoothing = true;
		 	this.addChild(new_bitmap);
		}
		
		
		private function scale_image(): void {
			var mtrx:Matrix = new Matrix();
			var scaleX:Number = 1;
 			var scaleY:Number = 1;
			
			var original_w:Number = image.width;
			var original_h:Number = image.height;
			var new_w:Number = this.width;
			var new_h:Number = this.height;
			var scale:Number = Math.min(original_w, original_h);
			var new_image:BitmapData;
			
			if(original_w > new_w || original_h > new_h){
				var sx:Number = new_w / original_w;
				var sy:Number = new_h / original_h;
				scale = Math.min(sx, sy);
				new_w = original_w * scale;
				new_h = original_h * scale;
				
				mtrx.scale(scale, scale);
				new_image = new BitmapData(new_w, new_h);
				new_image.draw(image, mtrx);
			}else{
				new_w = original_w;
				new_h = original_h;
				new_image = new BitmapData(new_w, new_h);
				new_image.draw(image);
			}
			
			this.width = new_w;
		 	this.height = new_h;
		 	
		 	var new_bitmap:Bitmap = new Bitmap(new_image);
		 	new_bitmap.smoothing = true;
		 	this.addChild(new_bitmap);
		 	//this.graphics.clear();
		 	//this.graphics.beginBitmapFill(new_image);
		 	//this.graphics.drawRect(0,0,new_image.width,new_image.height);
		 	//this.graphics.endFill();
		 	
		 	
		}
		
//---------------------------------------------------------------------
// Public properties
//---------------------------------------------------------------------
        
        /**
         * The relative width of the progress bar
         */
        public function set progressPercentWidth( value:Number ):void
        {
            _progressPercentWidth = value;
            evaluateProgressSize();
        }
        public function get progressPercentWidth():Number
        {
            return _progressPercentWidth;    
        }
        
        /**
         * The height of the progress bar
         */
        public function set progressHeight( value:Number ):void
        {
            _progressHeight = value;
            evaluateProgressSize();
            
        }
        public function get progressHeight():Number
        {
            return _progressHeight;
        }
        
        /**
         * The progress bar label
         */
        public function set progressLabel( value:String ):void
        {
            _progressBar.label = value;
        }
        public function get progressLabel():String
        {
            return _progressBar.label;
        }
        
        //---------------------------------------------------------------------
// Protected functions
//---------------------------------------------------------------------
        
        /**
         * Create children override
         * This is where the progress bar is created
         */
        override protected function createChildren():void
        {
            _progressBar = new ProgressBar();
            _progressBar.addEventListener( FlexEvent.CREATION_COMPLETE, progressCreated );
            _progressBar.visible = false;
            _progressBar.includeInLayout = false;
            
            _progressBar.mode = ProgressBarMode.EVENT;
            _progressBar.source = this.image_loader.contentLoaderInfo;
            
            _progressBar.label = "%3%%";
            _progressBar.labelPlacement = "bottom";
            _progressBar.setStyle("themeColor", "#60B72D");
            
            this.addChild( _progressBar );
        }
        
        /**
         * Set the dimensions of the progress bar
         */
        protected function evaluateProgressSize():void
        {
            if( _progressBar == null )
                return;
                
            _progressBar.x         = this.width * ( ( 1 - ( progressPercentWidth / 100 ) ) * 0.5 );
            _progressBar.y         = ( this.height * 0.5 ) - ( progressHeight * 0.5 );
            _progressBar.width     = this.width * ( progressPercentWidth / 100 );
            _progressBar.height = progressHeight
        }
        
        /**
         * Show the progress bar
         */
        protected function showProgress():void
        {
            // resets the progress bar before it is shown
            this.dispatchEvent( new ProgressEvent(ProgressEvent.PROGRESS, false, false, 0, 100 ) );
            
            _progressBar.visible = true;
        }
        
        /**
         * Hide the progress bar
         */
        protected function hideProgress():void
        {
            _progressBar.visible = false;
        }
        

//---------------------------------------------------------------------
// Event handlers
//---------------------------------------------------------------------
        
        private function progressCreated( event:FlexEvent ):void
        {
            evaluateProgressSize();
        }
        
        private function resizeHandler( event:ResizeEvent ):void
        {
            evaluateProgressSize();
        }
        
        private function openHandler( event:Event ):void
        {
            showProgress();
        }

        private function completeHandler( event:Event ):void
        {
            hideProgress();
        }
        
        private function ioErrorHandler( event:IOErrorEvent ):void
        {
            hideProgress();
        }

        private function securityErrorHandler( event:SecurityError ):void
        {
            hideProgress()
        }
		
	}
}